<template>
    <el-dialog :title="title" :visible.sync="openDlg" width="40%" append-to-body destroy-on-close class="uploadDlg">
        <div class="uploadBox">
            <div class="uploadBox-upBtn">
                <label>{{ uploadTitle }}：</label>
                <el-upload action="" class="upload-demo" ref="upload" :on-change="fileChange" :auto-upload="false"
                    :show-file-list="false">
                    <el-button size="small" type="text">选择文件</el-button>
                </el-upload>
            </div>
            <div class="uploadBox-upText">
                {{ fileName }}
            </div>
        </div>
        <div>{{ uploadTip }} <el-button
                v-if="fileType == 'scholarshipAllocation' || fileType == 'subsidyAllocation' || fileType == 'userscholarship' || fileType == 'userencouragement' || fileType == 'userdream' || fileType == 'usersoldier' || fileType == 'usersubsidy' || fileType == 'schoolScholarshipAllocation' || fileType == 'userschoolScholarship'"
                size="small" @click="downloadTemplate" type="text">下载模板</el-button></div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="openDlg = false">取 消</el-button>
        </div>
    </el-dialog>
</template>

<script>
let fileData = null
import request from '@/utils/request'
import { tansParams, blobValidate } from "@/utils/util";
import { saveAs } from 'file-saver'

import {
    editScholarshipPlan,
    editPoorStudent,
    schoolScholarshipUploadApply
} from "@/api/poorStudent-scholarship/plan.js";
import {
    editpoorStudentApplyType,
    editpoorStudentApplyTable
} from "@/api/poorStudent-scholarship/user.js";
import {
        scholarshipTypeArr
    } from "@/views/poorStudent-scholarship/dict.js"
export default {
    name: "uploadFile",
    props: {
        yearStr: {
            type: String,
            default: ''
        },
        studentType: {
            type: String,
            default: ''
        },
    },
    data() {
        return {
            title: '',
            openDlg: false,
            uploadTip: "只能上传word/pdf/zip/rar格式文件，且不超过20M!",
            uploadAction: '',
            fileType: '',
            fileName: '',
            uploadTitle: '',
            rowData: {},
            scholarshipType:'',
            scholarshipTypeArr
        }
    },
    computed: {
        userInfor() {
            return this.$store.state.user.userInfor;
        }
    },
    methods: {
        open(type, row, scholarshipType) {
            fileData = null
            this.fileType = type
            this.rowData = row ? JSON.parse(JSON.stringify(row)) : {}
            this.isSecondaryCollege = row?.isSecondaryCollege
            this.uploadTip = ""
            this.title = ""
            this.fileName = ""
            this.uploadAction = ""
            switch (type) {
                case 'scholarshipPlan':
                    this.title = '国家奖学金申请表'
                    this.uploadTitle = "申请表"
                    this.uploadTip = "只能上传word/pdf/zip/rar格式文件，且不超过20M!"
                    this.uploadAction = "/common/upload"
                    break;
                case 'encouragementPlan':
                    this.title = '国家励志奖学金申请表'
                    this.uploadTitle = "申请表"
                    this.uploadTip = "只能上传word/pdf/zip/rar格式文件，且不超过20M!"
                    this.uploadAction = "/common/upload"
                    break;
                case 'dreamPlan':
                    this.title = '筑梦奖学金申请表'
                    this.uploadTitle = "申请表"
                    this.uploadTip = "只能上传word/pdf/zip/rar格式文件，且不超过20M!"
                    this.uploadAction = "/common/upload"
                    break;

                case 'soldierPlan':
                    this.title = '退役士兵助学金申请表'
                    this.uploadTitle = "申请表"
                    this.uploadTip = "只能上传word/pdf/zip/rar格式文件，且不超过20M!"
                    this.uploadAction = "/common/upload"
                    break;
                case 'myApply':
                    this.title = '我的申请表'
                    this.uploadTitle = "申请表"
                    this.uploadTip = "只能上传word/pdf/zip/rar格式文件，且不超过20M!"
                    this.uploadAction = "/common/upload"
                    break;
               
                case 'SQ':
                    this.title = '申请表'
                    this.uploadTitle = "申请表"
                    this.uploadTip = "只能上传word/pdf/zip/rar格式文件，且不超过20M!"
                    this.uploadAction = "/common/upload"
                    break;
                case 'RD':
                    this.title = '认定表'
                    this.uploadTitle = "申请表"
                    this.uploadTip = "只能上传word/pdf/zip/rar格式文件，且不超过20M!"
                    this.uploadAction = "/common/upload"
                    break;
                case 'scholarshipAllocation':
                    this.title = '批量分配'
                    this.uploadTip = "只能上传.xlsx格式文件"
                    this.uploadTitle = "分配模板"
                    this.uploadAction = "/finances/nationalScholarshipApplyController/uploadTemplete"
                    this.scholarshipType = scholarshipType
                    break;
                case 'userscholarship':
                case 'userencouragement':
                case 'userdream':
                case 'usersoldier':
                    const scholarshipTypeItem = this.scholarshipTypeArr.find((item) => {return `user${item.code}` == type})
                    this.title = '批量上传'
                    this.uploadTip = "只能上传.xlsx格式文件"
                    this.uploadTitle = "分配模板"
                    this.uploadAction = `/finances/stuScholarshipApplyController/uploadTemplete?yearStr=${this.yearStr}&scholarshipType=${scholarshipTypeItem.typeId || ''}`
                    break;
                case 'usersubsidy':
                    this.title = '批量上传'
                    this.uploadTip = "只能上传.xlsx格式文件"
                    this.uploadTitle = "分配模板"
                    this.uploadAction = "/finances/diffStuPlanTypeController/uploadTemplete?yearStr=" + this.yearStr
                    break;
                case 'subsidyAllocation':
                    this.title = '批量分配'
                    this.uploadTip = "只能上传.xls格式文件"
                    this.uploadTitle = "分配模板"
                    this.uploadAction = "/finances/diffCollegePlanController/uploadTemplete?yearStr=" + this.yearStr
                    break;
                case 'schoolScholarshipSQ':
                    this.title = '申请表'
                    this.uploadTitle = "申请表"
                    this.uploadTip = "只能上传word/pdf/zip/rar格式文件，且不超过20M!"
                    this.uploadAction = "/common/upload"
                    break;
                case 'schoolScholarshipAllocation':
                    this.title = '批量分配'
                    this.uploadTip = "只能上传.xls格式文件"
                    this.uploadTitle = "分配模板"
                    this.uploadAction = "/finances/schScholarshipCollTypeController/upLoadTemplete?yearStr=" + this.yearStr
                    break;
                case 'userschoolScholarship':
                    this.title = '批量上传'
                    this.uploadTip = "只能上传.xlsx格式文件"
                    this.uploadTitle = "分配模板"
                    this.uploadAction = "/finances/schScholarshipStuCollController/uploadTemplete?yearStr=" + this.yearStr + "&isSecondaryCollege=" + this.isSecondaryCollege + '&studentType=' + this.studentType
                    break;
                default:
                    break;
            }
            this.openDlg = true
        },
        submitForm() {
            if (this.beforeAvatarUpload(fileData)) {
                let _formdata = new FormData()
                _formdata.append("file", fileData)
                let _config = {
                    headers: { 'Content-Type': 'multipart/form-data' }
                }
                if (this.fileType == 'userscholarship' || this.fileType == 'userencouragement' || this.fileType == 'userdream' || this.fileType == 'usersoldier' || this.fileType == 'userschoolScholarship') {
                    _config.responseType = "blob"
                }
                if (this.fileType == "scholarshipAllocation") {
                    _formdata.append("yearStr", this.yearStr)
                    _formdata.append("scholarshipType", this.scholarshipType)
                }
                request.post(this.uploadAction, _formdata, _config).then((res) => {
                    this.handleAvatarSuccess(res)
                }).catch(() => {
                    this.$message.error('上传失败！');
                })
            }
        },
        handleAvatarSuccess(res, file) {
            if (this.fileType == 'scholarshipAllocation' || this.fileType == 'subsidyAllocation' || this.fileType == 'schoolScholarshipAllocation') {
                // this.$confirm(res.msg, '上传结果', {
                //     confirmButtonText: '下载上传结果',
                //     cancelButtonText: '取消',
                //     type: ''
                // }).then(() => {
                //     this.openDlg = false
                //     this.$emit("onSearch")
                // }).catch(() => {
                //     this.openDlg = false
                //     this.$emit("onSearch")
                // });
                this.$modal.msgSuccess(res.msg);
                this.openDlg = false
                this.$emit("onSearch")
            }
            if (this.fileType == 'userscholarship' || this.fileType == 'userencouragement' || this.fileType == 'userdream' || this.fileType == 'usersoldier') {
                const isBlob = blobValidate(res);
                if (isBlob) {
                    const blob = new Blob([res])
                    saveAs(blob, "分配结果.xlsx")
                    this.$modal.msgSuccess("分配成功，请在已下载附件中查看分配结果！");
                    this.openDlg = false
                    this.$emit("onSearch")
                } else {
                    console.log(res.msg)
                    this.$message.error(res.msg || '上传失败！');
                }
                // window.open(res)
            }
            if (this.fileType == 'usersubsidy') {
                if (res.code == 200) {
                    this.downloadApply(res.msg, "分配结果")
                    this.$modal.msgSuccess("分配成功，请在已下载附件中查看分配结果！");
                    this.openDlg = false
                    this.$emit("onSearch")
                } else {
                    this.$modal.msgError(res.msg);
                }
            }
            if (this.fileType == 'userschoolScholarship') {
                const isBlob = blobValidate(res);
                if (isBlob) {
                    const blob = new Blob([res])
                    saveAs(blob, "校内奖学金学生名额分配结果.xlsx")
                    this.$modal.msgSuccess("分配成功，请在已下载附件中查看分配结果！");
                    this.openDlg = false
                    this.$emit("onSearch")
                }
            }
            if (['scholarshipPlan', 'encouragementPlan', 'dreamPlan', 'soldierPlan'].includes(this.fileType)) {
                this.rowData.fileName = res.originalFilename
                this.rowData.fileUrl = res.url
                editScholarshipPlan(this.rowData).then(() => {
                    this.$modal.msgSuccess("上传成功");
                    this.openDlg = false
                    this.$emit("onSearch")
                })
            }
            if (this.fileType == 'myApply') {
                editpoorStudentApplyTable({
                    id: this.rowData.id,
                    applyFileName: res.originalFilename,
                    applyFileUrl: res.url
                }).then(() => {
                    this.$modal.msgSuccess("上传成功");
                    this.openDlg = false
                    this.$emit("onSearch")
                    // editpoorStudentApplyType({
                    //     registerCode: this.userInfor.student.registerCode,
                    //     yearStr: this.rowData.yearStr,
                    //     id: this.rowData.id
                    // }).then(() => {
                    //     this.$modal.msgSuccess("上传成功");
                    //     this.openDlg = false
                    //     this.$emit("onSearch")
                    // })
                })

            }

            if (this.fileType == 'SQ') {
                this.rowData.applyFormName = res.originalFilename
                this.rowData.applyFormUrl = res.url
                editPoorStudent(this.rowData).then(() => {
                    this.$modal.msgSuccess("上传成功");
                    this.openDlg = false
                    this.$emit("onSearch")
                })
            }
            if (this.fileType == 'RD') {
                this.rowData.identifyFormName = res.originalFilename
                this.rowData.identifyFormUrl = res.url
                editPoorStudent(this.rowData).then(() => {
                    this.$modal.msgSuccess("上传成功");
                    this.openDlg = false
                    this.$emit("onSearch")
                })
            }
            if (this.fileType == 'schoolScholarshipSQ') {
                this.rowData.fileName = res.originalFilename
                this.rowData.fileUrl = res.url
                schoolScholarshipUploadApply(this.rowData).then(() => {
                    this.$modal.msgSuccess("上传成功");
                    this.openDlg = false
                    this.$emit("onSearch")
                })
            }
        },
        fileChange(file, fileList) {
            console.log(file, fileList)
            fileData = file.raw
            this.fileName = file.name
        },
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 20;
            if (this.fileType == 'scholarshipAllocation' || this.fileType == 'userscholarship' || this.fileType == 'userencouragement' || this.fileType == 'userdream' || this.fileType == 'usersoldier' || this.fileType == 'usersubsidy' || this.fileType == 'userschoolScholarship') {
                if (!["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"].includes(file.type)) {
                    this.$message.error('只能上传.xlsx格式文件!');
                    return false
                }
            } else if (this.fileType == 'subsidyAllocation' || this.fileType == 'schoolScholarshipAllocation') {
                if (!["application/vnd.ms-excel"].includes(file.type)) {
                    this.$message.error('只能上传.xls格式文件!');
                    return false
                }
            } else {
                if (!["application/pdf", "application/x-zip-compressed", "application/x-compressed", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword"].includes(file.type)) {
                    this.$message.error('只能上传word/pdf/zip/rar格式文件!');
                    return false
                }
            }
            if (!isLt2M) {
                this.$message.error('上传文件不能超过20MB!');
            }
            return isLt2M;
        },
        downloadApply(url, filename) {
            const link = document.createElement("a");
            const body = document.querySelector("body");
            link.href = url
            link.download = filename;
            link.style.display = "none";
            body.appendChild(link);
            link.click();
            body.removeChild(link);
        },
        downloadTemplate() {
            if (this.fileType == 'scholarshipAllocation') {
                this.download(
                    "/finances/nationalScholarshipApplyController/downloadTemplete?yearStr=" + this.yearStr +"&scholarshipType=" + this.scholarshipType,
                    {},
                    `奖学金学院名额分配模板.xlsx`
                );
            }
            if (this.fileType == 'subsidyAllocation') {
                this.download(
                    "/finances/diffCollegePlanController/downloadTemplete?yearStr=" + this.yearStr,
                    {},
                    `贫困生院系名额分配模板.xls`
                );
            }
            if (this.fileType == 'userscholarship' || this.fileType == 'userencouragement' || this.fileType == 'userdream' || this.fileType == 'usersoldier') {
                const scholarshipTypeItem = this.scholarshipTypeArr.find((item) => {return `user${item.code}` == this.fileType})
                if(scholarshipTypeItem) {
                    this.download(
                        "/finances/stuScholarshipApplyController/downloadTemplete?yearStr=" + this.yearStr + "&scholarshipType=" +  scholarshipTypeItem.typeId,
                        {},
                        `${scholarshipTypeItem.label}学生名额分配模板.xlsx`
                    );
                }
            }
            if (this.fileType == 'usersubsidy') {
                this.download(
                    "/finances/diffStuPlanTypeController/downloadTemplete?yearStr=" + this.yearStr,
                    {},
                    `贫困生学生名额分配模板.xlsx`
                );
            }
            if (this.fileType == 'schoolScholarshipAllocation') {
                this.download(
                    "/finances/schScholarshipCollTypeController/downLoadTemplete?yearStr=" + this.yearStr + "&isSecondaryCollege=" + this.isSecondaryCollege + '&studentType=' + this.studentType,
                    {},
                    `校内奖学金学院名额分配模板.xls`
                );
            }
            if (this.fileType == 'userschoolScholarship') {
                this.download(
                    "/finances/schScholarshipStuCollController/downloadTemplete?yearStr=" + this.yearStr + "&isSecondaryCollege=" + this.isSecondaryCollege,
                    {},
                    `校内奖学金学生名额分配模板.xlsx`
                );
            }
        }
    }

}
</script>

<style lang="scss" scoped>
.uploadDlg {
    ::v-deep .el-dialog__body {
        padding-top: 10px;
    }
}

.uploadBox {
    height: 66px;

    &-upBtn {
        display: flex;
        align-items: center;
    }
}
</style>